package com.prim.thread;

/**
 * 线程的终止/中止
 *
 * @author prim
 */
public class ThreadStop {
    public static void main(String[] args) throws InterruptedException {
//        interruptedThread();
        flagInterrupted();
    }



    private static void interruptedThread() throws InterruptedException {
        StopThread stopThread = new StopThread();
        stopThread.start();
        Thread.sleep(1000);
        //stop方法会导致线程安全问题 JDK不推荐在使用了
//        stopThread.stop();
        //线程的中断状态被清除 抛出异常 sleep interrupted 最终的输出结果是正确的
        stopThread.interrupt();
        while (stopThread.isAlive()) {
        }
        stopThread.print();
    }

    private volatile static boolean flag = true;

    /**
     * 推荐通过标志位 中止线程
     */
    public static void flagInterrupted() throws InterruptedException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (flag) {
                        System.out.println("运行中。。。。。。。。");
                        Thread.sleep(1000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        //3秒后flag改为false
        Thread.sleep(3000L);
        flag = false;
        System.out.println("程序运行结束");
    }
}
